//
//  ViewController.m
//  TZImagePickerControllerDemo
//
//  Created by Liyn on 2018/10/16.
//  Copyright © 2018 Liyn. All rights reserved.
//

#pragma mark - WeakSelf/StrongSelf

#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
#define StrongSelf(strongSelf) __strong __typeof(&*self) strongSelf = weakSelf;

#import "ViewController.h"
#import "MovEncodeToMpegTool.h"

#import <TZImagePickerController.h>

@interface ViewController ()<TZImagePickerControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"TZImagePickerController";
    // Do any additional setup after loading the view, typically from a nib.
}

/// 选择图片 非原图
- (IBAction)chosenPictures:(id)sender {
    
    //MaxImagesCount  可以选着的最大条目数
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1
                                                                                          delegate:self];
    // 是否显示可选原图按钮
    imagePicker.allowPickingOriginalPhoto = NO;
    // 是否允许显示视频
    imagePicker.allowPickingVideo = NO;
    // 是否允许显示图片
    imagePicker.allowPickingImage = YES;
    // 设置 模态弹出模式。 iOS 13默认非全屏
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    // 这是一个navigation 只能present
    [self presentViewController:imagePicker animated:YES completion:nil];
}

/// 选择图片 原图
- (IBAction)chosenPicturesOrgin:(id)sender {
    
    //MaxImagesCount  可以选着的最大条目数
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:3
                                                                                          delegate:self];
    // 是否显示可选原图按钮
    imagePicker.allowPickingOriginalPhoto = YES;
    // 是否允许显示视频
    imagePicker.allowPickingVideo = NO;
    // 是否允许显示图片
    imagePicker.allowPickingImage = YES;
    // 设置 模态弹出模式。 iOS 13默认非全屏
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    // 这是一个navigation 只能present
    [self presentViewController:imagePicker animated:YES completion:nil];
}

// 选择照片的回调
-(void)imagePickerController:(TZImagePickerController *)picker
      didFinishPickingPhotos:(NSArray<UIImage *> *)photos
                sourceAssets:(NSArray *)assets
       isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    NSLog(@"");
    /*
     photos
     <__NSArrayM 0x60000086a7c0>(
     <UIImage: 0x600002dd80e0>, {750, 1334}
     )
     */
    /*
     assets
     <__NSArrayM 0x600000868660>(
     <PHAsset: 0x7fb2d396dbd0> 4C784C4D-8CC3-4171-93E1-EDF0E9902D68/L0/001 mediaType=1/4, sourceType=1, (750x1334), creationDate=2018-08-29 02:59:19 +0000, location=0, hidden=0, favorite=0
     )
     */
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    
    options.version = PHImageRequestOptionsVersionCurrent;
    
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    
    PHImageManager *manager = [PHImageManager defaultManager];
    
    // 自己依靠asset取相册取image  固定大小的 缩略图
    [manager requestImageForAsset:assets[0]
                       targetSize:CGSizeMake(500, 500)
                      contentMode:PHImageContentModeDefault
                          options:options
                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        NSLog(@"resultHandler");
        // result <UIImage: 0x600002deeed0>, {750, 1334}
        
        /*
         Printing description of info:
         {
         PHImageFileOrientationKey = 0;
         PHImageResultDeliveredImageFormatKey = 4031;
         PHImageResultIsDegradedKey = 1;
         PHImageResultRequestIDKey = 66;
         PHImageResultWantedImageFormatKey = 4035;
         }
         
         */
    }];
    
    // 自己依靠asset取相册取image
    [manager requestImageDataForAsset:assets[0]
                              options:options
                        resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        // imageData <PLXPCData: 0x600003a754d0> length=304789
        // dataUTI public.jpeg
        // orientation    UIImageOrientationUp
        /*
         {
         PHImageFileSandboxExtensionTokenKey = "1343e4eecc38992aaacbc628399df9d81b0e7b46;00;00000000;00000000;00000000;000000000000001a;com.apple.app-sandbox.read;01;01000006;0000000001c32679;01;/users/liyn/library/developer/coresimulator/devices/9ff5edc7-edec-4d34-933f-f5fc27218f59/data/media/photodata/metadata/photodata/cplassets/group89/9703e1da-3139-4117-87ea-2d55a8fbddc5.jpg";
         PHImageFileURLKey = "file:///Users/liyn/Library/Developer/CoreSimulator/Devices/9FF5EDC7-EDEC-4D34-933F-F5FC27218F59/data/Media/PhotoData/Metadata/PhotoData/CPLAssets/group89/9703E1DA-3139-4117-87EA-2D55A8FBDDC5.JPG";
         PHImageResultDeliveredImageFormatKey = 3039;
         PHImageResultIsDegradedKey = 0;
         PHImageResultIsInCloudKey = 0;
         PHImageResultIsPlaceholderKey = 0;
         PHImageResultRequestIDKey = 67;
         PHImageResultWantedImageFormatKey = 9999;
         }
         */
        NSLog(@"");
    }];
    
    
}


/// 选择视频
- (IBAction)chosenVideos:(id)sender {
    
    //MaxImagesCount  可以选着的最大条目数
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:2 delegate:self];
    
    // 是否显示可选原图按钮
    imagePicker.allowPickingOriginalPhoto = NO;
    // 是否允许显示视频
    imagePicker.allowPickingVideo = YES;
    // 是否允许显示图片
    imagePicker.allowPickingImage = NO;
    // 持续时间 限制
    imagePicker.videoMaximumDuration = 5;
    // 设置 模态弹出模式。 iOS 13默认非全屏
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    // 这是一个navigation 只能present
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}


// 选择视频的回调
-(void)imagePickerController:(TZImagePickerController *)picker
       didFinishPickingVideo:(UIImage *)coverImage
                sourceAssets:(PHAsset *)asset{
    
    // <PHAsset: 0x141d68b70> A99AA1C3-7D59-4E10-A8D3-BF4FAD7A1BC6/L0/001 mediaType=2/0, sourceType=1, (1080x1920), creationDate=2018-06-04 09:32:53 +0000, location=1, hidden=0, favorite=0
    
    /// 包含该视频的基础信息
    PHAssetResource * resource = [[PHAssetResource assetResourcesForAsset: asset] firstObject];
    
    NSMutableArray *resourceArray = nil;
    
    if (@available(iOS 13.0, *)) {
        
        NSString *string1 = [resource.description stringByReplacingOccurrencesOfString:@" - " withString:@" "];
        
        NSString *string2 = [string1 stringByReplacingOccurrencesOfString:@": " withString:@"="];
        
        NSString *string3 = [string2 stringByReplacingOccurrencesOfString:@"{" withString:@""];
        
        NSString *string4 = [string3 stringByReplacingOccurrencesOfString:@"}" withString:@""];
        
        NSString *string5 = [string4 stringByReplacingOccurrencesOfString:@", " withString:@" "];
        
        resourceArray = [NSMutableArray arrayWithArray:[string5 componentsSeparatedByString:@" "]];
        
        [resourceArray removeObjectAtIndex:0];
        
        [resourceArray removeObjectAtIndex:0];
        
    } else {
        
        NSString *string1 = [resource.description stringByReplacingOccurrencesOfString:@"{" withString:@""];
        
        NSString *string2 = [string1 stringByReplacingOccurrencesOfString:@"}" withString:@""];
        
        NSString *string3 = [string2 stringByReplacingOccurrencesOfString:@", " withString:@","];
        
        resourceArray = [NSMutableArray arrayWithArray:[string3 componentsSeparatedByString:@" "]];
        
        [resourceArray removeObjectAtIndex:0];
        
        [resourceArray removeObjectAtIndex:0];
        
    }
    
    NSMutableDictionary *videoInfo = [[NSMutableDictionary alloc] init];
    
    for (NSString *string in resourceArray) {
        
        NSArray *array = [string componentsSeparatedByString:@"="];
        
        videoInfo[array[0]] = array[1];
        
    }
    
    videoInfo[@"duration"] = @(asset.duration).description;
    
    NSLog(@"%@",videoInfo);
    
    /*
     {
     assetLocalIdentifier = "A99AA1C3-7D59-4E10-A8D3-BF4FAD7A1BC6/L0/001";
     fileSize = 2212572;
     filename = "IMG_0049.MOV";
     size = "1080,1920";
     type = video;
     uti = "com.apple.quicktime-movie";
     }
     */
    
    
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    
    options.version = PHImageRequestOptionsVersionCurrent;
    
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    
    
    WS(weakSelf);
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:asset
                            options:options
                      resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        
        StrongSelf(strongSelf);
        
        NSString *sizeString = videoInfo[@"size"];
        
        NSArray *array = [sizeString componentsSeparatedByString:@","];
        
        CGSize size = CGSizeMake([array[0] floatValue], [array[1] floatValue]);
        
        [strongSelf choseVedioCompeletWithVedioAsset:(AVURLAsset *)asset
                                       andAVAudioMix:audioMix
                                        andVedioInfo:info
                                        andImageSize:size];
        
    }];
    
    
}

/// 收到转码结束回调
/// @param urlAsset 转码源文件
/// @param audioMix 转码源文件音频
/// @param vedioInfo 视频信息
/// @param size 视频文件大小
- (void)choseVedioCompeletWithVedioAsset:(AVURLAsset *)urlAsset
                           andAVAudioMix:(AVAudioMix *)audioMix
                            andVedioInfo:(NSDictionary *)vedioInfo
                            andImageSize:(CGSize)size{
    //[self showLoadingView:@"处理视频数据"];
    WS(weakSelf);
    [MovEncodeToMpegTool convertMovToMp4FromAVURLAsset:urlAsset
                                   andCompeleteHandler:^(NSURL * _Nonnull fileUrl) {
        StrongSelf(strongSelf);
        
        [strongSelf addVideoToTableCompeletWithVedioAsset:urlAsset
                                            andAVAudioMix:audioMix
                                             andVedioInfo:vedioInfo
                                             andImageSize:size
                                            andMP4FileUrl:fileUrl];
    }];
    
    
}

//1024*1024 MiByte 字节
#define VideoSizeMax  1024*1024

/// 收到转码结束回调
/// @param urlAsset 转码源文件
/// @param audioMix 转码源文件音频
/// @param vedioInfo 视频信息
/// @param size 视频文件大小
/// @param MP4FileUrl 转码后视频文件链接
- (void)addVideoToTableCompeletWithVedioAsset:(AVURLAsset *)urlAsset
                                andAVAudioMix:(AVAudioMix *)audioMix
                                 andVedioInfo:(NSDictionary *)vedioInfo
                                 andImageSize:(CGSize)size
                                andMP4FileUrl:(NSURL *)MP4FileUrl{
    if (MP4FileUrl == nil || MP4FileUrl.path == nil) {
        NSLog(@"视频获取失败") ;
        return;
    }
    
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    
    generator.appliesPreferredTrackTransform = YES;
    
    generator.maximumSize = CGSizeMake(size.width, size.height);
    
    NSError *error = nil;
    
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    
    // 截取 封面
    UIImage *image = [UIImage imageWithCGImage:img];
    
    NSLog(@"%@",image);
    
    NSError *mp4Rrror = nil;
    
    // 检查文件属性 查看文件大小 是否超标
    NSDictionary *infoDict = [[NSFileManager defaultManager]attributesOfItemAtPath:MP4FileUrl.path error:&mp4Rrror];
    
    NSString *fileSizeString = infoDict[@"NSFileSize"];
    
    if (fileSizeString && !error) {
        
        NSInteger fileSize = fileSizeString.integerValue;
        
        // 检查转码后的视频大小，压缩率一般可以达到5-10
        // 视频限制大小 单位兆字节 MiByte
        
        NSInteger capacity = 15;
        
        if (fileSize>VideoSizeMax*capacity) {
            
            NSLog(@"%@", [NSString stringWithFormat:@"视频最大不能超过%ldM",capacity]);
            
            // 删除已转码的视频
            
            [[NSFileManager defaultManager] removeItemAtPath:MP4FileUrl.path error:&error];
            
        }
    }
    else{
        
        NSLog(@"视频获取失败");
        
        [[NSFileManager defaultManager] removeItemAtPath:MP4FileUrl.path error:&error];
        
    }
    
}
@end
